// Copyright (c) 2011 SameGoal LLC.
// All Rights Reserved.
// Author: Andy Hochhaus <ahochhaus@samegoal.com>

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NET_HTTP_SERVER_COMET_TIMER_WRAPPER_H_
#define NET_HTTP_SERVER_COMET_TIMER_WRAPPER_H_

#include <event2/event.h>

#include <map>
#include <string>

#include "base/basictypes.h"

// Enhance basic evtimer functionality by:
//   a) Using event_base_init_common_timeout to optimize for common timeout
//      values (eg: 2 sec, 30 sec)
//   b) Exposing a higher level timer interface (eg: Reset, Stop).

namespace sg {
namespace net {
namespace http {
namespace server {
namespace comet {

class TimerWrapper {
 public:
  TimerWrapper(const uint64 &seconds, std::function<void()> cb);

  ~TimerWrapper();

  // Call Init once after creation of the event_base. Do not call multiple
  // times or once per TimerWrapper instance. Init sets up common_timeout
  // intervals.
  static void Init(struct event_base *base);

  void Reset(const uint64 &seconds);

  void Stop();

  // TimerCallbackInternal is used internally to dispatch close events to the
  // relevant {Session,ProxyDetect} timer callbacks. This should not be called
  // as part of the public interface.
  static void TimerCallbackInternal(int fd, int16_t event, void *arg);

 private:
  std::function<void()> cb_;
  struct ::event *ev_;

  static struct timeval secs2_;
  static struct timeval secs30_;
  static struct event_base *base_;

  DISALLOW_COPY_AND_ASSIGN(TimerWrapper);
};

}  // namespace comet
}  // namespace server
}  // namespace http
}  // namespace net
}  // namespace sg

#endif  // NET_HTTP_SERVER_COMET_TIMER_WRAPPER_H_
